package com.flower.utils;

import com.flower.domain.vo.farmer.FlowerEncyclopediaDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 花卉爬虫工具类
 */
@Slf4j
@Component
public class FlowerCrawler {

    /**
     * 爬取索引页，获取详情页URL列表
     */
    public static List<String> crawlIndexPage(String indexUrl, String selector) throws IOException {
        List<String> detailUrls = new ArrayList<>();
        
        // 设置请求头，模拟浏览器
        Document doc = Jsoup.connect(indexUrl)
                .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                .timeout(10000)
                .get();
        
        // 根据选择器获取详情页链接
        Elements links = doc.select(selector);
        for (Element link : links) {
            String href = link.attr("href");
            if (StringUtils.isNotBlank(href)) {
                // 处理相对路径
                if (href.startsWith("/")) {
                    href = indexUrl.substring(0, indexUrl.indexOf("/", 8)) + href;
                } else if (!href.startsWith("http")) {
                    href = indexUrl + "/" + href;
                }
                detailUrls.add(href);
            }
        }
        
        return detailUrls;
    }

    /**
     * 批量爬取花卉数据
     */
    public static List<FlowerEncyclopediaDetailVO> batchCrawl(List<String> urls) {
        List<FlowerEncyclopediaDetailVO> results = new ArrayList<>();
        
        for (String url : urls) {
            try {
                // 添加延时，避免请求过快
                TimeUnit.SECONDS.sleep(2);
                
                FlowerEncyclopediaDetailVO flower = crawlFlowerDetail(url);
                if (flower != null) {
                    results.add(flower);
                }
            } catch (Exception e) {
                log.error("爬取花卉数据失败: {}", url, e);
            }
        }
        
        return results;
    }
    
    /**
     * 爬取花卉详情页
     */
    public static FlowerEncyclopediaDetailVO crawlFlowerDetail(String url) throws IOException {
        // 设置请求头，模拟浏览器
        Document doc = Jsoup.connect(url)
                .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                .timeout(10000)
                .get();
        
        // 创建百科详情对象
        FlowerEncyclopediaDetailVO detailVO = new FlowerEncyclopediaDetailVO();
                
                // 提取基本信息
        detailVO.setName(extractText(doc, "h1.flower-name"));
        detailVO.setScientificName(extractText(doc, "div.scientific-name"));
        detailVO.setAlias(extractText(doc, "div.alias"));
        detailVO.setFamily(extractText(doc, "div.family"));
        detailVO.setGenus(extractText(doc, "div.genus"));
        detailVO.setOrigin(extractText(doc, "div.origin"));
        detailVO.setIntroduction(extractText(doc, "div.introduction"));
        detailVO.setFeatures(extractText(doc, "div.features"));
        
        // 设置养护难度
        String difficultyStr = extractText(doc, "div.difficulty");
        try {
            detailVO.setCultivationDifficulty(Integer.parseInt(difficultyStr));
        } catch (NumberFormatException e) {
            detailVO.setCultivationDifficulty(3); // 默认中等难度
        }
        
        // 设置缩略图
        Element thumbnailElement = doc.select("img.flower-thumbnail").first();
        if (thumbnailElement != null) {
            detailVO.setThumbnail(thumbnailElement.attr("src"));
        }
        
        // 设置生长环境
        FlowerEncyclopediaDetailVO.FlowerGrowingEnvironmentVO environmentVO = 
            new FlowerEncyclopediaDetailVO.FlowerGrowingEnvironmentVO();
        environmentVO.setLightRequirement(extractText(doc, "div.light-requirement"));
        environmentVO.setWaterRequirement(extractText(doc, "div.water-requirement"));
        environmentVO.setSoilType(extractText(doc, "div.soil-type"));
        environmentVO.setHumidity(extractText(doc, "div.humidity"));
        environmentVO.setFertilization(extractText(doc, "div.fertilization"));
        detailVO.setGrowingEnvironment(environmentVO);
        
        // 提取生长阶段信息
        Elements stageElements = doc.select("div.growth-stage");
                if (!stageElements.isEmpty()) {
            List<FlowerEncyclopediaDetailVO.FlowerGrowthStageVO> growthStages = new ArrayList<>();
            int sortOrder = 1;
                    
                    for (Element stageElement : stageElements) {
                FlowerEncyclopediaDetailVO.FlowerGrowthStageVO stageVO = 
                    new FlowerEncyclopediaDetailVO.FlowerGrowthStageVO();
                stageVO.setStageName(extractText(stageElement, "h3.stage-name"));
                stageVO.setStageDescription(extractText(stageElement, "div.stage-description"));
                stageVO.setDuration(extractText(stageElement, "div.duration"));
                stageVO.setCareTips(extractText(stageElement, "div.care-tips"));
                stageVO.setSortOrder(sortOrder++);
                
                // 提取阶段图片
                Elements imageElements = stageElement.select("img.stage-image");
                if (!imageElements.isEmpty()) {
                    List<FlowerEncyclopediaDetailVO.FlowerImageVO> stageImages = new ArrayList<>();
                    for (Element imageElement : imageElements) {
                        FlowerEncyclopediaDetailVO.FlowerImageVO imageVO = 
                            new FlowerEncyclopediaDetailVO.FlowerImageVO();
                        imageVO.setImageUrl(imageElement.attr("src"));
                        imageVO.setDescription(imageElement.attr("alt"));
                        stageImages.add(imageVO);
                    }
                    stageVO.setImages(stageImages);
                }
                
                growthStages.add(stageVO);
            }
            
            detailVO.setGrowthStages(growthStages);
        }
        
        // 提取栽培方法
        Elements methodElements = doc.select("div.cultivation-method");
        if (!methodElements.isEmpty()) {
            List<FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO> cultivationMethods = new ArrayList<>();
            int sortOrder = 1;
            
            for (Element methodElement : methodElements) {
                FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO methodVO = 
                    new FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO();
                methodVO.setMethodName(extractText(methodElement, "h3.method-name"));
                methodVO.setMethodContent(extractText(methodElement, "div.method-content"));
                methodVO.setSuitableSeason(extractText(methodElement, "div.suitable-season"));
                methodVO.setSortOrder(sortOrder++);
                cultivationMethods.add(methodVO);
            }
            
            detailVO.setCultivationMethods(cultivationMethods);
        }
        
        // 提取花卉图片
        Elements galleryElements = doc.select("div.flower-gallery img");
        if (!galleryElements.isEmpty()) {
            List<FlowerEncyclopediaDetailVO.FlowerImageVO> images = new ArrayList<>();
            int sortOrder = 1;
            
            for (Element imgElement : galleryElements) {
                FlowerEncyclopediaDetailVO.FlowerImageVO imageVO = 
                    new FlowerEncyclopediaDetailVO.FlowerImageVO();
                imageVO.setImageUrl(imgElement.attr("src"));
                imageVO.setDescription(imgElement.attr("alt"));
                imageVO.setImageType(1); // 默认全株
                imageVO.setIsMain(sortOrder == 1 ? 1 : 0); // 第一张为主图
                imageVO.setSortOrder(sortOrder++);
                images.add(imageVO);
            }
            
            detailVO.setImages(images);
        }
        
        return detailVO;
    }
    
    /**
     * 提取文本内容
     */
    private static String extractText(Document doc, String selector) {
        Element element = doc.select(selector).first();
        return element != null ? element.text().trim() : "";
    }
    
    /**
     * 提取文本内容
     */
    private static String extractText(Element element, String selector) {
        Element selectedElement = element.select(selector).first();
        return selectedElement != null ? selectedElement.text().trim() : "";
    }
} 